package com.dh.api.gateway.filter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import com.dh.api.gateway.constant.CookieConstant;
import com.dh.api.gateway.constant.RedisConstant;
import com.dh.api.gateway.utils.CookieUtil;
import com.dh.api.gateway.utils.IRedisService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @author 作者 dinghao
 * @version 创建时间：2018年11月20日 上午11:22:54
 * @Description 类说明 : 权限拦截区分买家和卖家
 */
@Component
public class AuthSellerFilter extends ZuulFilter {

	@Autowired
	private IRedisService iRedisService;

	@Override
	public String filterType() {
		return PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return PRE_DECORATION_FILTER_ORDER - 1;
	}

	@Override
	public boolean shouldFilter() {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		if ("/order-server/order/finish".equals(request.getRequestURI())) {
			return true;
		}
		return false;
	}

	@Override
	public Object run() {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		/**
		 * /order/create 只能买家访问(cookie里面有openid) /order/finish
		 * 只能卖家访问(cookie里面有token,并且对应的redis中有值) /product/list 都能访问
		 */
		Cookie cookie = CookieUtil.get(request, "token");
		if (cookie == null || StringUtils.isEmpty(cookie.getValue()) || StringUtils
				.isEmpty((String) iRedisService.get(String.format(RedisConstant.TOKEN_TEMPLATE, cookie.getValue())))) {
			requestContext.setSendZuulResponse(false);
			requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
		}
		return null;
	}

}
